package com.ai.module.chat.config.interceptor;

import cn.hutool.http.HttpStatus;
import com.ai.module.chat.common.ano.NoAuth;
import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.constant.RedisKeyStringConstant;
import com.ai.module.chat.common.constant.StringConstant;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.user.domain.vo.UserLoginInfo;
import com.ai.module.chat.util.RedisTemplateUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Enumeration;

/**
 * @author: MrHe
 * @create: 2023-09-02 10:42
 * @description:
 **/
@Configuration
@Slf4j
public class MangeUserInterceptor implements HandlerInterceptor {

 

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取用户,设置时间 token:0ac80a41-04a4-48c6-b179-2bdcdf0ef4ae
        String requestURI = request.getRequestURI();
        String headToken = request.getHeader(StringConstant.TOKEN);
        if (StringUtils.isBlank(headToken)){
           // headToken ="3c15d3fa-116b-4cd9-8d3e-c56ecfbff944@01-26_23_47_33";

        }

        // getHeaderToken(request);
       // request.he(StringConstant.TOKEN, "3c15d3fa-116b-4cd9-8d3e-c56ecfbff944@01-26_23_47_33");
        if (handler instanceof  HandlerMethod){
            HandlerMethod methodHandle = (HandlerMethod) handler;
            Method method = methodHandle.getMethod();
            boolean noAuth = method.isAnnotationPresent(NoAuth.class);
            if (noAuth && StringUtils.isBlank(headToken)){
                log.warn("无需校验,直接操作......");
                return true;
            }
        }

        if(request.getMethod().equals("OPTIONS")){
            return true;
        }else{
           // token = request.getHeader(StringConstant.TOKEN);
        }

        //String userToken = String.format(StringConstant.USER_TOKEN, uuid);
        if (StringUtils.isBlank(headToken)){
            response.setStatus(401);
            log.error("用户登录操作拦截,登录失效requestURI [{}],headToken [{}]",requestURI,headToken);
            throw new BusinessException( 401,"请重新登录");
        }
        String userTokenKey = String.format(RedisKeyStringConstant.USER_INFO, headToken);
        UserLoginInfo userLoginInfo =  RedisTemplateUtils.get(userTokenKey);
        if (userLoginInfo ==null){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new BusinessException("登录已过期,请重新登录",401);
        }
        ThreadLocalContext.set(StringConstant.TOKEN, headToken);
        ThreadLocalContext.set(StringConstant.USER_INFO,userLoginInfo);
        ThreadLocalContext.set(StringConstant.CURRENT_TIME,System.currentTimeMillis());
        ThreadLocalContext.setUserLoginInfo(userLoginInfo);

        return true;
    }

    private static String getHeaderToken(HttpServletRequest request) {
        String token = StringPool.EMPTY;

        //request.getHeader(StringConstant.TOKEN);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String header = headerNames.nextElement();
            if (StringConstant.TOKEN.equalsIgnoreCase(header)){
                token = request.getHeader(header);

                return token;
            }
        }
        return token;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        ThreadLocalContext.clear();
    }

}
